'use strict';

const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const request = require('request');
const path = require('path');

const ds = require('./defaultstate.js');
const ds_raw = Object.assign({}, ds);

app.set('views', path.join(__dirname, '../dist'));
app.set('view engine', 'ejs');
app.set('view cache', true);

app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../dist')));

/**
 *  显示图书馆页面的请求有两个来源：1.来自微信公众号的图文消息  2.来自普通浏览器，
 *  *注：微信公众号的图文消息是指点击畅校园公众号内部的图书馆功能时，返回的图文消息
 *
 *  当请求来源为 1 时，cookie中带有id字段，里面存储用户微信的openid，通过微信
 *  图书馆API(https://code.creatshare.com/Back-end/cxy_book)可根据openid
 *  查询用户信息，实现自动登录。
 */

app.get('/', (req, res) => {

    const cookie = req.cookies;

    // 有id则说明请求来自微信
    if (cookie.id) {
        request({
            'url': 'http://test.changxiaoyuan.com',
            'qs': {
                'do': 'wxlogin',
                'OpenID': cookie.id,
                'sub': true
            }
        }, (err, msg, body) => {
            if (err) {
                console.log(err);
            }

            body = JSON.parse(body);

            switch (cookie.action) {
                // 点击最大的图文消息进入图书馆（未绑定／已绑定）
                case 'search':
                    if (body.bind !== 0) {
                        ds.defaultUserState = geState(body, ds.defaultUserState, cookie);
                    }
                    break;

                // 点击图文消息的绑定账号（未绑定） 
                case 'bind':
                    // 显示userpanel
                    ds.defaultUserState.unrender.isSpread = true;
                    ds.defaultUserState.unrender.needchange = false;
                    // 更改登陆模式为绑定
                    ds.defaultUserState.unrender.isGoBind = true;
                    break;

                // 点击图文消息的借、藏、期、续（已绑定）                    
                case 'center':
                    if (body.bind !== 0) {
                        ds.defaultUserState = geState(body, ds.defaultUserState);
                    }
                    // 显示userpanel
                    ds.defaultUserState.unrender.isSpread = true;
                    ds.defaultUserState.unrender.needchange = false;
                    break;

                // 根据微信的关键字搜索图书后，查看某本书的详情（已绑定／未绑定）                    
                case 'bookdetail':
                    if (body.bind !== 0) {
                        ds.defaultUserState = geState(body, ds.defaultUserState);
                    }
                    ds.defaultBookState.unrender.keyword = cookie.keyword;
                    ds.defaultBookState.unrender.offset = cookie.index;
                    ds.defaultAsideState.unrender.isSpread = true;
                    ds.defaultAsideState.render.book = JSON.parse(cookie.current);
                    ds.defaultAsideState.render.isLike = body.bind !== 0 ? ds.defaultUserState.render.subscibe.some(b => b.ctrlid === ds.defaultAsideState.render.book.detail) : false;
                    break;

                // 根据微信的关键字搜索图书后，点击查看更多按钮（已绑定／未绑定）                    
                case 'more':
                    if (body.bind !== 0) {
                        ds.defaultUserState = geState(body, ds.defaultUserState);
                    }
                    ds.defaultBookState.unrender.keyword = cookie.keyword;
                    ds.defaultBookState.unrender.offset = cookie.index;
            }

            res.render('index', { 'defstate': JSON.stringify({ ds, ds_raw }) });
        })
    } else {
        res.render('index', { 'defstate': JSON.stringify({ ds, ds_raw }) });
    }


});

function geState(body, oldstate, cookie = {}) {
    oldstate.render.bind = true;
    oldstate.render.book = body.book;
    oldstate.render.subscibe = body.sub_book;
    oldstate.render.timestamp = Math.round(new Date().getTime() / 1000);
    oldstate.render.user = body.username;
    oldstate.unrender.isLogin = true;
    oldstate.unrender.isBind = true
    oldstate.unrender.WXID = cookie.id;
    return oldstate;
}

app.listen(8000);